const app = getApp()
const date = new Date()
const mtm_utils = require("../common/utils/mtm_utils.js")
Page({

  /**
   * 页面的初始数据
   */
  data: {
    custSourceListData: app.globalData.custSourceListData,
    custStatuListData: app.globalData.custStatuListData,
    yearListData: app.globalData.yearListData,
    mileageListData: app.globalData.mileageListData,
    colorListData: app.globalData.colorListData,
    cityListData: app.globalData.cityListData,
    carNoRegionList: app.globalData.carNoRegionList,
    storeListData: app.globalData.storeListData,
    request_common_para: app.globalData.request_common_para,
    index: 0,
    chosen: '',
    id: '',
    cust_name: '',
    cust_tel: '',
    carType: 0,
    car_model: "+",
    begin_price: '',
    end_price: '',
    note: '',
    other_car_no_region: "",
    messageList: [],
    updateDateFormat: '',
    isDisabled: true,
    date: '--请选择--', //date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate(),
    bookTime:'--请选择--',
    strartdate: date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate(),
    isYearShow: false,
    initYearVal: "不限",
    isMileageShow: false,
    initMileageVal: "不限",
    isCarColorShow: false,
    initCarColorVal: "其他",
    isCarSales: false,
    vinCode: '',
    isDateDisabled:false,
    isbookTimeDisabled:false
  },
  bindPickerChange: function(e) {
    this.setData({
      index: e.detail.value
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that=this
    app.intiSysConfigData()
    this.setData({
      custSourceListData: app.globalData.custSourceListData,
      storeListData: app.globalData.storeListData
    })
    wx.request({
      url: app.getHost()+"/datalake/v1/userManages/" + options.id,
      method: "GET",
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: res => {
        if (res.statusCode == 200) {
          //console.info("客户需求列表：" + JSON.stringify(res.data))
          var custSourceListData = this.data.custSourceListData;
          for (var i in custSourceListData) {
            custSourceListData[i].checked = false
            if (custSourceListData[i].name == res.data.customerSource) {
              custSourceListData[i].checked = true
            }
          }
          var custStatuListData = this.data.custStatuListData
          for (var i in custStatuListData) {
            custStatuListData[i].checked = false
            if (custStatuListData[i].name == res.data.state_name) {
              custStatuListData[i].checked = true
            }
          }
          var colorListData = this.data.colorListData
          var requirementColors = res.data.requirementColor.split("|")
          for (var i in colorListData) {
            colorListData[i].checked = false
            for (var k in requirementColors) {
              if (colorListData[i].name == requirementColors[k]) {
                colorListData[i].checked = true
              }
            }
          }
          var requirementYears = res.data.requirementYear.split("|")
          var yearListData = this.data.yearListData
          for (var i in yearListData) {
            yearListData[i].checked = false
            for (var k in requirementYears) {
              if (yearListData[i].name == requirementYears[k]) {
                yearListData[i].checked = true
              }
            }
          }
          var mileageListData = this.data.mileageListData
          var requirementMileages = res.data.requirementMileage.split("|")
          for (var i in mileageListData) {
            mileageListData[i].checked = false
            for (var k in requirementMileages) {
              if (mileageListData[i].name == requirementMileages[k]) {
                mileageListData[i].checked = true
              }
            }
          }
          var requirementSettled_in = res.data.requirementSettled_in
          var other_car_no_region = ""
          let carNoRegionList = this.data.carNoRegionList
          for (let i in carNoRegionList) {
            if (requirementSettled_in == carNoRegionList[i].value) {
              carNoRegionList[i].checked = true
            } else if (requirementSettled_in != "沪A" && requirementSettled_in != "沪C" && requirementSettled_in != "") {
              carNoRegionList[i].checked = true
              other_car_no_region = requirementSettled_in
            }
          }
          let store_name=res.data.store_name
          let storeListData = app.globalData.storeListData
          for (var i in storeListData) {
            if (storeListData[i] == store_name) {
              this.setData({ index: i })
              break;
            }
          }
          let vinCode=res.data.vin_code;
          if(vinCode){
            this.setData({ 
              isCarSales:true,
              vinCode:vinCode
              })
          }
          let carTypeCount = res.data.carModel.split(",").length
          let carModels = res.data.carModel

          let req_data = this.data.request_common_para;
          req_data.customerPhone = res.data.customerPhone;
          //跟进时间
          let follow_time = res.data.follow_time
          if (follow_time) {
            //this.setData({ date: follow_time})
          }

          req_data.carModel = res.data.carModel.split(",")
          wx.request({
            url: app.getHost()+'/datalake/v1/userManages/messages',
            data: req_data,
            method: "POST",
            success: res => {
              let messageList = []
              for (let i in res.data.list) {
                let message = {}
                let obj = res.data.list[i]
                let update_time = obj.update_time
                let user_type = obj.user_type
                let update_user = obj.update_user
                let content = obj.content
                let user_manager_record_id = obj.user_manager_record_id
                let forword_book_record_details_page = obj.forword_book_record_details_page
                message.update_time = update_time
                message.user_type = user_type
                message.update_user = update_user
                message.content = content
                message.user_manager_record_id=user_manager_record_id
                message.forword_book_record_details_page=forword_book_record_details_page
                if (user_type.length > 0 && user_type != "url" && user_type != "null") {
                  let k = content.indexOf("到店") + 2
                  let pageId = content.substr(k)
                  let content_str = content.substring(0, k)
                  message.user_type = app.getHost()+ "/datalake/v1/direct/error/" + pageId
                  message.content = content_str
                }
                messageList.push(message)
              }

              this.setData({
                messageList: messageList,
                request_common_para: app.globalData.request_common_para
              })

            },
            fail: function(res) {

            },
            complete: function(res) {

            }
          })

          this.setData({
            id: res.data.id,
            cust_name: res.data.customerName,
            cust_tel: res.data.customerPhone,
            custSourceListData: custSourceListData,
            custStatuListData: custStatuListData,
            colorListData: colorListData,
            yearListData: yearListData,
            mileageListData: mileageListData,
            car_model: carModels,
            begin_price: res.data.budgetLimitMin,
            end_price: res.data.budgetLimitMax,
            carNoRegionList: carNoRegionList,
            note: res.data.note,
            other_car_no_region: other_car_no_region,
            updateDateFormat: res.data.updateDateFormat,
            carType: carTypeCount,
            initYearVal: res.data.requirementYear,
            initMileageVal: res.data.requirementMileage,
            initCarColorVal: res.data.requirementColor
          })
        }
      },
      complete: function(res) {}
    });


  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  /**
   * 表单提交事件
   */
  submitCustInfo: function(e) {
    let form_id = e.detail.formId
    try {
      if (form_id) {
        app.saveFormId(form_id)
      }
    } catch (e) {
      console.info("app.saveFormId err" + e);
    }
    let req_data = this.data.request_common_para;
    let city =""// this.data.cityListData[this.data.index]
    let store_name = this.data.storeListData[this.data.index]
    let cust = e.detail.value
    let id = cust.id
    let cust_name = cust.cust_name //客户姓名
    if (!cust_name) {
      app.noTitlemodalTap("请输入客户姓名")
      return;
    }
    let cust_tel = cust.cust_tel //客户电话
    if (!cust_tel) {
      app.noTitlemodalTap("请输入客户手机")
      return;
    }
    cust_tel = cust_tel.replace(/ /g, "").replace("-", "")
    if (!mtm_utils.isValidMobile(cust_tel)) {
      app.noTitlemodalTap("该号码不合法")
      return;
    }
    let car_source = cust.car_source //客户来源
    if (!car_source) {
      app.noTitlemodalTap("请选择客户来源")
      return;
    }

    let cust_status = cust.cust_status //购车意向
    if (!cust_status) {
      app.noTitlemodalTap("请选择意向等级")
      return;
    }
    var begin_price = cust.begin_price //价格
    var end_price = cust.end_price
    if (!begin_price || !end_price) {
      app.noTitlemodalTap("请输入购车预算")
      return;
    }
    if (end_price * 1 < begin_price * 1) {
      app.noTitlemodalTap("请输入正确的购车预算")
      return;
    }
    let car_model = cust.car_model.split(',');
    car_model = car_model.join(',');
    /*let car_model = ""
    let car_model1 = cust.car_model1 //车型 
    let car_model2 = cust.car_model2;
    if (car_model1 != '+') {
      car_model = car_model1
    }
    if (car_model2 != '+') {
      car_model = car_model2
    }
    if (car_model1 != '+' && car_model2 != '+') {
      car_model = car_model1 + "," + car_model2;
    }*/
    if (car_model == '' || car_model == '+') {
      app.noTitlemodalTap("请输入车型")
      return;
    }
    let car_year_val = this.data.initYearVal
    /**
    let car_year_list = cust.year_list //年限
    let car_year_val = "";
    for (var i in car_year_list) {
      car_year_val += car_year_list[i]
      if (i != car_year_list.length - 1) {
        car_year_val += "|"
      }
    }
    if (!car_year_val) {
      app.noTitlemodalTap("请选择年限要求")
      return;
    }
     */
    let car_mileage_val = this.data.initMileageVal
    /**
    let car_mileage_list = cust.mileage_list //里程
    for (let i in car_mileage_list) {
      car_mileage_val += car_mileage_list[i];
      if (i != car_mileage_list.length - 1) {
        car_mileage_val += "|"
      }
    }
    if (!car_mileage_val) {
      app.noTitlemodalTap("请选择里程要求")
      return;
    }
  */
    let car_color_val = this.data.initCarColorVal
    /**
    let car_color_list = cust.car_color //颜色
   
    for (let i in car_color_list) {
      car_color_val += car_color_list[i]
      if (i != car_color_list.length - 1) {
        car_color_val += "|"
      }
    }
    if (!car_color_val) {
      app.noTitlemodalTap("请选择颜色要求")
      return;
    }
     */
    let car_no_region = cust.car_no_region //落地户
    let note = cust.note //备注

    let other_car_no_region = cust.other_car_no_region //外地车牌
    /**
    if (!car_no_region) {
      app.noTitlemodalTap("请选择落地户")
      return;
    }
     */
    if (car_no_region == "外地") {
      if (!other_car_no_region) {
        app.noTitlemodalTap("请输入外地车牌")
        return;
      }
      car_no_region = other_car_no_region
    }
    app.toast3Tap()
    req_data.id = id
    req_data.form_id = form_id
    req_data.audit = 0
    req_data.budgetLimitMax = end_price
    req_data.budgetLimitMin = begin_price
    req_data.carModel = car_model
    req_data.city = city
    req_data.store_name=store_name
    req_data.customerName = cust_name
    req_data.customerPhone = cust_tel
    req_data.customerSource = car_source
    req_data.note = note
    req_data.requirementColor = car_color_val
    req_data.requirementMileage = car_mileage_val
    req_data.requirementSettled_in = car_no_region
    req_data.requirementYear = car_year_val
    req_data.state_name = cust_status
    if (req_data.id != '') {
      console.info("page updCust submit params:" + JSON.stringify(req_data))
      wx.request({
        url: app.getHost()+'/datalake/v1/userManages/' + id,
        data: req_data,
        method: "PUT",
        header: {
          'content-type': 'application/json' // 默认值
        },
        success: function(res) {
          if (res.statusCode == 200) {
            app.toast1Tap()
            wx.reLaunch({
              url: 'custInfoList',
            })
          }else if(res.statusCode==500){
            app.noTitlemodalTap(res.data.message)
          }
        },
        complete: function(res) {},
        fail: function(res) {
          console.error(res);
        }
      })
    }
  },
  userTypeUrl: function(e) {
    var id = e.currentTarget.id
    wx.navigateTo({
      url: '../out/out?html_src=' + id,
    })
  },
  toBookRecordDetails: function (e) {
    console.info(e)
    var id = e.currentTarget.id
    wx.navigateTo({
      url: 'bookRecordDetails?id=' + id,
    })
  },
  validTelBindblur: function(e) {
    var tel = e.detail.value
    var that = this
    wx.request({
      url: app.getHost()+'/datalake/v1/userManages?Customerphone=' + tel,
      method: "GET",
      success: function(res) {
        console.info(res.data.length)
        if (res.data.length > 0) {
          app.noTitlemodalTap("该号码已存，不允许新建几录")
          that.setData({
            cust_tel: ''
          })
        }
      }
    })
  },
  bindinputCarModel: function(e) {
    wx.navigateTo({
      url: 'carModelType?selectedCarModelType=' + this.data.car_model + '&carType=' + this.data.carType
    })
  },
  btnSave: function(e) {
    this.setData({
      isDisabled: false
    })
  },
  followCustInfo: function(e) { //跟进客户信息
    let form_id = e.detail.formId
    try {
      if (form_id) {
        app.saveFormId(form_id)
      }
    } catch (e) {
      console.info("app.saveFormId err" + e);
    }

    let cust = e.detail.value
    let content = cust.content
    let follow_time = (this.data.date == '--请选择--' ? '' : this.data.date)
    let book_time=(this.data.bookTime == '--请选择--' ? '' : this.data.bookTime)
    if (!content && !follow_time && !book_time){
      app.noTitlemodalTap("跟进记录不能空")
      return;
    }
    // if (!content) {
    //   app.noTitlemodalTap("跟进记录不能空")
    //   return;
    // }
    app.toast3Tap()
    let req_data = {};
    req_data = this.data.request_common_para
    req_data.id = this.data.id
    req_data.audit = 0
    req_data.content = content
    req_data.customerPhone = this.data.cust_tel
    req_data.form_id = form_id
    req_data.follow_time = follow_time
    req_data.book_time = book_time
    console.info("page updCust followCustInfo params:" + JSON.stringify(req_data))
    wx.request({
      url: app.getHost()+'/datalake/v1/userManages/' + req_data.id,
      data: req_data,
      method: "PUT",
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function(res) {
        if (res.statusCode == 200) {
          app.toast1Tap()
          wx.reLaunch({
            url: 'custInfoList',
          })
        }
      },
      complete: function(res) {
        console.info(JSON.stringify(res))
      },
      fail: function(res) {
        console.error(res);
      }
    })
  },
  bindDateChange: function(e) {
    
    this.setData({
      date: e.detail.value
    })
    if (e.detail.value != "--请选择--") {
      this.setData({
        isbookTimeDisabled: true
      })
    }
  },
  bindBookTimeChange: function (e) {
    this.setData({
      bookTime: e.detail.value
    })
    if (e.detail.value != "--请选择--") {
      this.setData({
        isDateDisabled: true
      })
    }

  },
  bindcancelFollowTime: function(e) {
    this.setData({
      date: '--请选择--',
      isbookTimeDisabled: false
    })
  },
  bindCancelBookTime: function (e) {
    this.setData({
      bookTime: '--请选择--',
      isDateDisabled: false
    })
  },
  bindtapisYearShow: function(e) {
    if (this.data.isYearShow) {
      this.setData({
        isYearShow: false
      })
    } else {
      this.setData({
        isYearShow: true
      })
    }
  },
  bindchangeYear: function(e) {
    let year_check_list = e.detail.value;
    let val = "";
    for (let i in year_check_list) {
      val += year_check_list[i]
      if (i != year_check_list.length - 1) {
        val += "|"
      }
    }
    if (val == "") {
      val = "不限"
    }
    this.setData({
      initYearVal: val
    })
  },
  bindtapisMileageShow: function(e) {
    if (this.data.isMileageShow) {
      this.setData({
        isMileageShow: false
      })
    } else {
      this.setData({
        isMileageShow: true
      })
    }
  },
  bindchangeMileage: function(e) {
    let mileage_list = e.detail.value;
    let val = "";
    for (let i in mileage_list) {
      val += mileage_list[i]
      if (i != mileage_list.length - 1) {
        val += "|"
      }
    }
    if (val == "") {
      val = "不限"
    }
    this.setData({
      initMileageVal: val
    })
  },
  bindtapisCarColorShow: function(e) {
    if (this.data.isCarColorShow) {
      this.setData({
        isCarColorShow: false
      })
    } else {
      this.setData({
        isCarColorShow: true
      })
    }
  },
  bindchangeCarColor: function(e) {
    let car_color_list = e.detail.value;
    let val = "";
    for (let i in car_color_list) {
      val += car_color_list[i]
      if (i != car_color_list.length - 1) {
        val += "|"
      }
    }
    if (val == "") {
      val = "不限"
    }
    this.setData({
      initCarColorVal: val
    })
  },
  bindtapCallTel: function(e) {
    if (this.data.cust_tel) {
      wx.makePhoneCall({
        phoneNumber: this.data.cust_tel,
        success: res => {

        }
      })
    }
  },
  isCarSalesBindtap: function (e) {
    
    this.setData({
      isCarSales: this.data.isCarSales ? false : true
    })
    if(!this.data.isCarSales){
      this.setData({vinCode:''})
    }
  }
})